<template>
  <div class="strategies">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="container">
        <div class="row align-items-center">
          <div class="col-md-8">
            <h1 class="page-title">热门攻略</h1>
            <p class="page-subtitle">精选实用的旅行攻略，让你的旅程更加完美</p>
          </div>
          <div class="col-md-4 text-md-end">
            <el-button type="primary" size="large" @click="goToCreate">
              <el-icon><DocumentAdd /></el-icon>
              写攻略
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 热门标签 -->
    <div class="tags-section">
      <div class="container">
        <div class="tags-header mb-3">
          <h3><i class="bi bi-tags"></i> 热门标签</h3>
        </div>
        <div class="tags-container">
          <el-tag
            v-for="tag in hotTags"
            :key="tag.name"
            :type="selectedTag === tag.name ? 'primary' : ''"
            :effect="selectedTag === tag.name ? 'dark' : 'plain'"
            @click="selectTag(tag.name)"
            class="tag-item"
            size="large"
          >
            {{ tag.name }} ({{ tag.count }})
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="container">
        <div class="filter-card">
          <div class="row align-items-center">
            <div class="col-lg-4 col-md-6 mb-3">
              <el-input
                v-model="filters.keyword"
                placeholder="搜索攻略标题、内容..."
                @keyup.enter="handleSearch"
                clearable
              >
                <template #prepend>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <div class="col-lg-2 col-md-3 col-sm-6 mb-3">
              <el-select v-model="filters.destination" placeholder="目的地" @change="handleSearch" clearable>
                <el-option
                  v-for="dest in destinations"
                  :key="dest"
                  :label="dest"
                  :value="dest"
                />
              </el-select>
            </div>
            <div class="col-lg-2 col-md-3 col-sm-6 mb-3">
              <el-select v-model="filters.type" placeholder="攻略类型" @change="handleSearch" clearable>
                <el-option label="交通攻略" value="traffic" />
                <el-option label="美食攻略" value="food" />
                <el-option label="住宿攻略" value="accommodation" />
                <el-option label="景点攻略" value="attraction" />
                <el-option label="购物攻略" value="shopping" />
              </el-select>
            </div>
            <div class="col-lg-2 col-md-3 col-sm-6 mb-3">
              <el-select v-model="filters.sortBy" placeholder="排序方式" @change="handleSearch">
                <el-option label="最新发布" value="createTime" />
                <el-option label="最多浏览" value="viewCount" />
                <el-option label="最多收藏" value="collectCount" />
                <el-option label="最高评分" value="rating" />
              </el-select>
            </div>
            <div class="col-lg-2 col-md-3 col-sm-6 mb-3">
              <el-button type="primary" @click="handleSearch" style="width: 100%">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 攻略列表 -->
    <div class="strategies-section">
      <div class="container">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        
        <div v-else-if="strategies.length === 0" class="empty-container">
          <el-empty description="暂无攻略数据">
            <el-button type="primary" @click="goToCreate">写第一篇攻略</el-button>
          </el-empty>
        </div>
        
        <div v-else class="strategies-list">
          <div
            v-for="strategy in strategies"
            :key="strategy._id"
            class="strategy-item"
            @click="goToStrategy(strategy._id)"
          >
            <div class="strategy-image">
              <img :src="strategy.cover" :alt="strategy.title" />
              <div class="strategy-type">{{ getTypeLabel(strategy.type) }}</div>
            </div>
            <div class="strategy-content">
              <div class="strategy-header">
                <h3 class="strategy-title">{{ strategy.title }}</h3>
                <div class="strategy-rating">
                  <el-rate v-model="strategy.rating" disabled show-score />
                </div>
              </div>
              <p class="strategy-summary">{{ strategy.content }}</p>
              <div class="strategy-tags">
                <el-tag
                  v-for="tag in strategy.tags"
                  :key="tag"
                  size="small"
                  effect="plain"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <div class="strategy-meta">
                <div class="author-info">
                  <img :src="strategy.author.avatar" :alt="strategy.author.username" class="author-avatar" />
                  <span class="author-name">{{ strategy.author.username }}</span>
                  <span class="publish-date">{{ formatDate(strategy.createTime) }}</span>
                </div>
                <div class="strategy-stats">
                  <span><i class="bi bi-eye"></i> {{ formatNumber(strategy.viewCount) }}</span>
                  <span><i class="bi bi-bookmark"></i> {{ formatNumber(strategy.likeCount) }}</span>
                  <span><i class="bi bi-chat"></i> {{ formatNumber(strategy.viewCount) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="totalPages > 1">
          <el-pagination
            v-model:current-page="pagination.page"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            layout="prev, pager, next, jumper, total"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { defaultAvatar, images } from '@/assets/images'
import { 
  ElButton, ElInput, ElSelect, ElOption, ElIcon, ElTag, 
  ElSkeleton, ElEmpty, ElPagination, ElRate, ElMessage 
} from 'element-plus'
import { Search, DocumentAdd } from '@element-plus/icons-vue'
import {getGuideList} from '@/api/data'
const router = useRouter()

// 响应式数据
const loading = ref(false)
const strategies = ref<any[]>([])
const selectedTag = ref('')

// 筛选条件
const filters = reactive({
  keyword: '',
  destination: '',
  type: '',
  sortBy: 'createTime'
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 热门标签
const hotTags = ref([
  { name: '交通攻略', count: 156 },
  { name: '美食推荐', count: 243 },
  { name: '住宿指南', count: 189 },
  { name: '景点打卡', count: 334 },
  { name: '购物指南', count: 98 },
  { name: '省钱技巧', count: 267 },
  { name: '行程规划', count: 178 },
  { name: '摄影攻略', count: 145 }
])

// 目的地选项
const destinations = ref(['北京', '上海', '广州', '深圳', '成都', '西安', '杭州', '南京', '重庆', '天津', '云南', '西藏', '新疆', '三亚'])

// 计算属性
const totalPages = computed(() => Math.ceil(pagination.total / pagination.pageSize))

// 选择标签
const selectTag = (tagName: string) => {
  if (selectedTag.value === tagName) {
    selectedTag.value = ''
  } else {
    selectedTag.value = tagName
    filters.keyword = tagName
  }
  handleSearch()
}

// 跳转到攻略详情
const goToStrategy = (strategyId: number) => {
  router.push({ name: 'PostDetail', params: { id: strategyId } })
}

// 跳转到创建攻略
const goToCreate = () => {
  ElMessage.info('创建攻略功能开发中...')
}

// 搜索处理
const handleSearch = async () => {
  pagination.page = 1
  await loadStrategies()
}

// 页码变化处理
const handlePageChange = (page: number) => {
  pagination.page = page
  loadStrategies()
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 获取类型标签
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    traffic: '交通',
    food: '美食',
    accommodation: '住宿',
    attraction: '景点',
    shopping: '购物'
  }
  return typeMap[type] || '攻略'
}

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}

// 加载攻略数据
const loadStrategies = async () => {
  loading.value = true
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    const mockStrategies = Array.from({ length: pagination.pageSize }, (_, index) => {
      const globalIndex = (pagination.page - 1) * pagination.pageSize + index
      return {
        id: globalIndex + 1,
        title: `${destinations.value[globalIndex % destinations.value.length]}旅游完全攻略 ${globalIndex + 1}`,
        summary: '详细的旅游攻略，包含交通、住宿、美食、景点等全方位信息，助你玩转这座城市...',
        cover: [images.img20221106190735, images.img90, images.img980, images.imgOIP][globalIndex % 4],
        type: ['traffic', 'food', 'accommodation', 'attraction', 'shopping'][globalIndex % 5],
        rating: 4 + Math.random(),
        tags: hotTags.value.slice(globalIndex % 3, (globalIndex % 3) + 3).map(tag => tag.name),
        author: {
          id: globalIndex + 1,
          username: `攻略达人${globalIndex + 1}`,
          avatar: defaultAvatar
        },
        viewCount: Math.floor(Math.random() * 50000),
        collectCount: Math.floor(Math.random() * 5000),
        commentCount: Math.floor(Math.random() * 500),
        createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString()
      }
    })
    const  res = await getGuideList()
    console.log(res.data)
    strategies.value = res.data
    pagination.total = 150 // 模拟总数
  } catch (error) {
    console.error('加载攻略失败:', error)
    ElMessage.error('加载攻略失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadStrategies()
})
</script>

<style scoped>
.page-header {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  padding: 60px 0;
}

.page-title {
  font-size: 3rem;
  font-weight: 700;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 1.2rem;
  opacity: 0.9;
  margin: 0;
}

.tags-section {
  padding: 30px 0;
  background: #f8f9fa;
}

.tags-header h3 {
  color: #333;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.tags-header i {
  color: #f5576c;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s;
  padding: 8px 16px;
  border-radius: 20px;
}

.tag-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 87, 108, 0.3);
}

.filter-section {
  padding: 30px 0;
  background: white;
}

.filter-card {
  background: #f8f9fa;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.strategies-section {
  padding: 40px 0;
}

.loading-container,
.empty-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.strategies-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.strategy-item {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  cursor: pointer;
  display: flex;
  height: 200px;
}

.strategy-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.strategy-image {
  width: 300px;
  position: relative;
  overflow: hidden;
}

.strategy-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.strategy-item:hover .strategy-image img {
  transform: scale(1.05);
}

.strategy-type {
  position: absolute;
  top: 15px;
  left: 15px;
  background: rgba(245, 87, 108, 0.9);
  color: white;
  padding: 5px 12px;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
}

.strategy-content {
  flex: 1;
  padding: 25px;
  display: flex;
  flex-direction: column;
}

.strategy-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.strategy-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin: 0;
  flex: 1;
}

.strategy-rating {
  margin-left: 15px;
}

.strategy-rating :deep(.el-rate) {
  line-height: 1;
}

.strategy-summary {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 15px;
  flex: 1;
}

.strategy-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.strategy-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  object-fit: cover;
}

.author-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.publish-date {
  font-size: 12px;
  color: #999;
}

.strategy-stats {
  display: flex;
  gap: 15px;
}

.strategy-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.strategy-stats i {
  color: #f5576c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

@media (max-width: 768px) {
  .page-header {
    padding: 40px 0;
    text-align: center;
  }
  
  .page-title {
    font-size: 2.2rem;
  }
  
  .strategy-item {
    flex-direction: column;
    height: auto;
  }
  
  .strategy-image {
    width: 100%;
    height: 200px;
  }
  
  .strategy-content {
    padding: 20px;
  }
  
  .strategy-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .strategy-rating {
    margin-left: 0;
  }
  
  .strategy-meta {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}
</style>


